#include <iostream>
#include <string>
#include <cstring>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdlib>
#include <unistd.h>

#define SIZE 1024

void Usage(const std::string &proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

// ./tcpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
  
    // 客户端 要和 服务端进行通信,也要创建 TCP 套接字
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = INADDR_ANY;

    while (true)
    {
        // 1.创建套接字
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(sockfd < 0){
            std::cerr << "socket error..." << std::endl;
            return 1; 
        }
        // 2.因为 client 并不需要绑定套接字,所有直接 connect 建立链接即可
        int n = connect(sockfd, (const sockaddr*)&server, sizeof(server));
        if(n < 0){
            std::cerr << "connect error..." << std::endl;
            return 2;
        }
        // 3.发送信息
        while (true)
        {
            std::string message;
            std::cout << "Please Enter@ ";
            getline(std::cin, message);

            int m = write(sockfd, message.c_str(), message.size());
            if(m < 0){
                std::cerr << "write error..." << std::endl;
                break;
            }

            // 获取 服务器处理后的信息
            char inbuffer[SIZE*4];
            m = read(sockfd, inbuffer, sizeof(inbuffer));
            if(m > 0){
                inbuffer[m] = 0;
                std::cerr << inbuffer << std::endl;
            }
            else{
                break;
            }
        }
        close(sockfd);
    }
    

    return 0;
}